package cn.bus.controller;

import cn.bus.domain.Customer;
import cn.bus.service.CustomerService;
import cn.bus.service.RentService;
import cn.bus.vo.RentVo;
import cn.sys.domain.User;
import cn.sys.utils.DataGridView;
import cn.sys.utils.RandomUtils;
import cn.sys.utils.ResultObj;
import cn.sys.utils.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author Mxb
 * @version 1.0
 * @date 2019/11/4 15:13
 */
@RestController
@RequestMapping("rent")
public class RentController {
    @Autowired
    private RentService rentService;

    @Autowired
    private CustomerService customerService;


    @RequestMapping("checkCustomerExist")
    public ResultObj checkCustomerExist(RentVo rentVo) {
        Customer customer = customerService.queryCustomerById(rentVo.getIdentity());
        if (customer != null) {
            return ResultObj.STATUS_TRUE;
        } else {
            return ResultObj.STATUS_ERROR;
        }
    }

    /**
     * 初始化添加出租单的表单数据
     */
    @RequestMapping("initRentFrom")
    public RentVo initRentFrom(RentVo rentVo) {
        //生成出租单号                                          号单前缀
        rentVo.setRentid(RandomUtils.createRandomStringUseTime("CZ"));
        //设置起租时间
        rentVo.setBegindate(new Date());

        User user = (User) WebUtils.getHttpSession().getAttribute("user");
        //设置操作员
        rentVo.setOpername(user.getRealname());
        return rentVo;
    }

    /**
     * 保存出租单信息
     */
    @RequestMapping("saveRent")
    public ResultObj saveRent(RentVo rentVo) {
        try {
            //设置创建时间
            rentVo.setCreatetime(new Date());
            //设置归还状态    0：未归还   1：归还
            rentVo.setRentflag(0);

            //保存
            this.rentService.addRent(rentVo);

            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    //查询出租单
    @RequestMapping("loadAllRent")
    public DataGridView loadAllRent(RentVo rentVo) {
        return this.rentService.queryAllRent(rentVo);
    }

    /**
     * 修改出租单信息
     */
    @RequestMapping("updateRent")
    public ResultObj updateRent(RentVo rentVo) {
        try {
            //保存
            this.rentService.updateRent(rentVo);

            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }


    /**
     * 删除租单信息
     */
    @RequestMapping("deleteRent")
    public ResultObj deleteRent(RentVo rentVo) {
        try {
            this.rentService.deleteRent(rentVo.getRentid());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

}

